package cn.rengy.web.framework.shiro.realm;

import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.rengy.web.framework.principal.LocalIdentity;
import cn.rengy.web.framework.shiro.credential.RetryLimitPasswordMatcher;
import cn.rengy.web.framework.shiro.token.LocalToken;
import cn.rengy.web.framework.sys.user.entity.UserAuth;
import cn.rengy.web.framework.sys.user.service.UnionUserService;
import cn.rengy.web.framework.sys.user.service.UserService;
/**
 * 用户名密码登录
 * @author rengy
 *
 */
@Component
public class UsernamePasswordRealm extends IAuthorizingRealm{

	@Autowired
	private UserService userService;
	
	@Autowired
	private UnionUserService unionUserService;
	
	public UsernamePasswordRealm(RetryLimitPasswordMatcher retryLimitPasswordMatcher){
		super(retryLimitPasswordMatcher);
		//this.setAuthenticationCachingEnabled(true);
	}	
	public boolean supports(AuthenticationToken token) {
        return token instanceof LocalToken; //仅支持LocalToken类型的Token
    }
	private static Logger logger = LoggerFactory.getLogger(UsernamePasswordRealm.class);
	/**
	 * 登录认证
	 * @see 执行subject.login()时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
		if (!(authenticationToken instanceof LocalToken)) {
            throw new AuthenticationException("token不匹配");
        }
		LocalToken token=(LocalToken)authenticationToken;
		String username=(String)token.getPrincipal();
		//查询本地登录认证信息
		Map<String,Object> user=userService.getUserByUserName(username);
		if(user==null){
			throw new UnknownAccountException("用户名或密码错误");
		}
		Long userLoginId=(Long)user.get("id");
		//查询统一用户信息
		UserAuth userAuth=unionUserService.getUnionUserByAuthId(userLoginId);
    	if(userAuth==null) {
    		throw new UnknownAccountException("用户不存在");
    	}
    	LocalIdentity identity=new LocalIdentity();
    	identity.setUlid(userLoginId);
    	identity.setUserid(userAuth.getUser_id());
    	identity.setClientId(token.getClientId());
        return new SimpleAuthenticationInfo(identity, user.get("password"), getName());
        //logger.debug("验证当前Subject时获取到token为：" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); 
	}
}
